# -*- coding:utf-8 -*-
# CCTV官方
import requests, re, datetime,json,os

from bs4 import BeautifulSoup as bs

headers = {
    'User-Agent' : 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)'
                   ' AppleWebKit/537.36 (KHTML, like Gecko)'
                   ' Chrome/99.0.4844.82 Safari/537.36'
}

def get_channels_cctv():
    channels = []
    host = 'https://tv.cctv.com'
    url = '%s/epg/index.shtml' % host
    res = requests.get(url, headers=headers)
    res.encoding = 'utf-8'
    soup = bs(res.text, 'html.parser')
    lis = soup.select('div.channel_con > div > ul > li')
    need_date = datetime.datetime.now().strftime('%Y%m%d')
    for li in lis:
        id = li.select('img')[0].attrs['title'].strip()
        logo = 'http://' + li.select('img')[0].attrs['src'].strip()
        url_info = 'http://api.cntv.cn/epg/getEpgInfoByChannelNew?c=%s&serviceId=tvcctv&d=%s&t=jsonp&cb=set' % (id, need_date)
        # print(url_info)
        res = requests.get(url_info,headers = headers,timeout = 5)
        res.encoding = 'utf-8'
        research = re.search('"channelName":"(.+?)".+?"lvUrl":"(.+?)"',res.text)
        name = research.group(1)
        url = research.group(2)
        channel = {
            'name': name,
            'id': [id],
            'url': url,
            'source': 'cctv',
            'logo': logo,
            'desc': '',
            'sort':'央视',
        }
        channels.append(channel)
    return channels

# 处理节目列表
def get_programs_cctv(channel, channel_id, dt, func_arg):
    programs = []
    msg = ''
    success = 1
    need_date = dt.strftime('%Y%m%d')
    url = 'http://api.cntv.cn/epg/getEpgInfoByChannelNew?c=%s&serviceId=tvcctv&d=%s&t=jsonp&cb=set'%(channel_id,need_date)
    try:
        res = requests.get(url, headers=headers,timeout=5)
        res.encoding = 'utf-8'
        programs = json.loads(re.search('set\((.*)\)', res.text).group(1))
        prog_lists = programs['data'][channel_id]['list']
        for prog_list in prog_lists:  #
            title = prog_list['title'] #节目名称
            starttime = datetime.datetime.fromtimestamp(prog_list['startTime']) #开始时间
            endtime=datetime.datetime.fromtimestamp(prog_list['endTime']) #结束时间
            program = {'channel_id': channel.id,
                       'starttime': starttime,
                       'endtime': endtime,
                       'title': title,
                       'desc': '',
                       'program_date': dt,
                       }
            programs.append(program)
        programlen = len(programs)
    except Exception as e:
        success = 0
        spidername = os.path.basename(__file__).split('.')[0]
        msg = 'spider-%s- %s' % (spidername,e)
    ret = {
        'success': success,
        'programs': programs,
        'msg': msg,
        'last_program_date': dt,
        'ban':0,
    }
    return ret

def serialize_datetime(obj):
    if isinstance(obj, datetime.datetime):
        return obj.isoformat()
    raise TypeError("Type not serializable")

def main():
    channels = get_channels_cctv()
    date = datetime.datetime.now().strftime('%Y%m%d')
    channels_list = []
    epgs = []
    print('开始获取CCTV节目单:')
    for channel in channels:
        try:
            print('正在获取%s节目单...' % channel['name'])
            programs = get_programs_cctv(channel, channel['id'][0], datetime.datetime.now(), {})
            
            #  <channel id="1"><display-name lang="zh">CCTV1</display-name></channel>
            # print('<channel id="%s"><display-name lang="zh">%s</display-name></channel>' % (channel['id'][0], channel['name']))
            channel_id = channel['id'][0]
            if channel_id == 'cctvjilu':
            	channel_id = 'cctv9'
            if channel_id == 'cctvchild':
            	channel_id = 'cctv14'
            if channel_id == 'cctv5plus':
            	channel_id = 'cctv5+'	
            channels_list.append(f'{channel_id}#{channel["name"]}')
            epgs.append('<channel id="%s"><display-name lang="zh">%s</display-name></channel>' % (channel_id, channel['name']))
            programme = programs['programs']['data'][channel['id'][0]]['list']
            # <programme start="20240807040000 +0800" stop="20240807041220 +0800" channel="1"><title lang="zh">2024秘境之眼-峭壁精灵黑叶猴(4K)</title><desc lang="zh"></desc></programme>
            for programme in programme:
                # 时间转换格式为start="20240807040000 +0800" stop="20240807041220 +0800"
                start = programme['startTime']
                start = datetime.datetime.fromtimestamp(start)
                start_str = start.strftime('%Y%m%d%H%M%S +0800')
                end = programme['endTime']
                end = datetime.datetime.fromtimestamp(end)
                end_str = end.strftime('%Y%m%d%H%M%S +0800')
                title = programme['title']
                # print('<programme start="%s" stop="%s" channel="%s"><title lang="zh">%s</title><desc lang="zh"></desc></programme>' % (start_str, end_str, channel['id'][0], title))
                epgs.append('<programme start="%s" stop="%s" channel="%s"><title lang="zh">%s</title><desc lang="zh"></desc></programme>' % (start_str, end_str, channel_id, title))
        except Exception as e:
            print('获取%s节目单失败：%s' % (channel['name'], e))
            pass
    # 获取path，获取当前路径
    # 日期格式为20240807
    dt = datetime.datetime.now().strftime('%Y%m%d')

    print('正在保存CCTV节目单...')
    # id与频道名称对照表
    # 保存到当前路径下的channel文件夹中，文件名为cctv_channels_20240807.txt
    channels_path = os.path.dirname(os.path.abspath(__file__))+f'/channel/cctv_channels_{dt}.txt'
    # 保存txt格式
    with open(channels_path, 'w', encoding='utf-8') as f:
        f.write('\n'.join(channels_list))
        f.close()
    print('CCTV节目单保存成功！')
    print('正在保存CCTV节目单xml格式...')
    # 保存到当前路径下的channel文件夹中，文件名为cctv_20240807.xml
    path = os.path.dirname(os.path.abspath(__file__))+f'/channel/cctv_{dt}.xml'
    # 保存xml格式
    with open(path, 'w', encoding='utf-8') as f:
        heade_str='''<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE tv SYSTEM "http://nas.laoknas.com:8181/epg/get_epg_xml.dtd">
<tv>\n'''
        heade_str = heade_str + '\n'.join(epgs) +'\n</tv>'
        f.write(heade_str)
        f.close()
    print('CCTV节目单xml格式保存成功！')
    print('CCTV节目单获取完成！')
    # epg_xml = open('cctv.xml', 'r', encoding='utf-8').read()
    return  heade_str


if __name__ == '__main__':
    main()
